package com.myopen.model;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import com.jfinal.kit.StrKit;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Model;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.activerecord.Record;
import com.myopen.kit.IpKit;
import com.myopen.kit.RequestKit;
import com.myopen.kit.UUIDKit;

public class Log extends Model<Log>{

	private static final long serialVersionUID = -6408995522291184390L;
	public static final Log dao=new Log();
	
	public Page<Record> pagequery(Record record){
		StringBuffer sqlExceptSelect=new StringBuffer("from t_log t "
				+ " left join t_user u on t.creator=u.id"
				+ " where t.removed='0' and t.show='0' ");
		List<Object> list=new ArrayList<Object>();
		
		if(!StrKit.isBlank(record.getStr("searchContent"))){
			sqlExceptSelect.append(" and (t.info like ? or u.username like ?) ");
			list.add("%"+record.getStr("searchContent")+"%");
			list.add("%"+record.getStr("searchContent")+"%");
		}

		sqlExceptSelect.append(" order by t.createTime desc");
		return Db.paginate(record.getInt("pageNumber"),record.getInt("pageSize"),"select t.*,u.username,u.nickname,u.email,u.cellphone ",sqlExceptSelect.toString(),list.toArray());		
	}

	/**
	 * 添加可以查询出来的数据
	 */
	public void addShowLog(String userId,String info,String type){
		saveLog(userId,info,"0",type);
	}

	/**
	 * 添加页面上无需显示的日志，一般用于开发人员查看
	 */
	public void addHideLog(String userId,String info,String type){
		saveLog(userId,info,"1",type);
	}

	private void saveLog(String userId,String info,String show,String type){
		HttpServletRequest request=RequestKit.getTl().get();
		String ip=null;
		String ua=null;
		if(request!=null){
			ip=IpKit.getRealIpV2(request);
			ua=request.getHeader("user-agent");
		}

		Record bo=new Record();
		Date now=new Date();
		bo.set("id", UUIDKit.getUUID());
		bo.set("createTime", now);
		bo.set("updateTime", now);
		bo.set("creator", userId);
		bo.set("updator", userId);
		bo.set("ip", ip);
		bo.set("info", info);
		bo.set("ua", ua);
		bo.set("show", show);
		bo.set("type", type);
		Db.save("t_log", bo);

	}

}
